package com.hongxun.design.activitys;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.TypedValue;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hongxun.design.MyApp;
import com.hongxun.design.R;
import com.hongxun.design.adapters.MaterialDetailAdapter;
import com.hongxun.design.bean.MaterialBean;
import com.hongxun.design.constant.Constant;
import com.hongxun.design.interfaces.HeadSecond;
import com.hongxun.design.listeners.ListenerSet;
import com.hongxun.design.mytools.IconSourse;
import com.hongxun.design.mytools.IntentToActivity;
import com.hongxun.design.mytools.MString;
import com.hongxun.design.mytools.SetTypeface;
import com.hongxun.design.mytools.ShardPreferencesTool;
import com.hongxun.design.mytools.ToastShow;
import com.hongxun.design.ui.dialogstyle.MyDialog;
import com.hongxun.design.ui.headandbottonpanel.HeadSecondControlPanel;
import com.hongxun.design.ui.ui_listview.Swipemenulistview.SwipeMenu;
import com.hongxun.design.ui.ui_listview.Swipemenulistview.SwipeMenuCreator;
import com.hongxun.design.ui.ui_listview.Swipemenulistview.SwipeMenuItem;
import com.hongxun.design.ui.ui_listview.Swipemenulistview.SwipeMenuListView;
import com.hongxun.design.ui.ui_listview.refreshlist.SwipeRefreshListView;
import com.hongxun.design.utils.DataUtil;
import com.hongxun.design.utils.PopwindowUtil;
import com.hongxun.design.utils.fastjson.FastJsonUtil;
import com.hongxun.design.utils.httputil.HttpStringUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zerdoor_pc on 2016/5/23.
 * 典设、模块——材料明细
 */
public class MaterialDetailActivity extends BaseActivity implements HeadSecond {
    int type;
    int isGone;
    final int ADDADAPTER = 1;
    String codeset_id;
    String title;
    Handler handler;
    Handler NowHandler;
    Handler upExpMaterialHandler;
    SwipeRefreshListView codeset_list;
    List<MaterialBean> data, delList;
    MaterialDetailAdapter adapter;
    int mposition = -1;
    int cposition = -1;
    boolean isRefesh = false;
    //批量删除
    private LinearLayout layoutDel;
    private CheckBox checkBox;
    private int count = -1;
    private boolean isLong = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_materialdetail2);
        findBar();
        findView();
    }

    @SuppressLint("NewApi")
    private void getIntentData() {
        Bundle bundle = getIntent().getExtras();
        type = bundle.getInt(MString.TYPE);
        codeset_id = bundle.getString(MString.codeset_id);
        if (type == Constant.EDIT) {
            title = bundle.getString(MString.TITLE, "编辑材料明细");
            if (title.length() > 14) {
                title = title.substring(0, 14) + "...";
            }
            isGone = View.VISIBLE;
        } else if (type == Constant.EdMeterial) {//操作典设材料
            title = "典设材料明细";
            isGone = View.VISIBLE;
        } else if (type == Constant.EdModel) {//操作模块材料
            title = "模块材料明细";
            isGone = View.VISIBLE;
        } else {
            title = "材料明细";
            isGone = View.GONE;
        }
    }

    @Override
    public void findBar() {
        getIntentData();
        HeadSecondControlPanel headsecond_layout = (HeadSecondControlPanel) findViewById(R.id.design_head);
        headsecond_layout.initHeadPanel(DataUtil.getsecondbean(IconSourse.ADD + "", isGone,
                R.color.bar_right, ListenerSet.back, title, R.color.title, View.VISIBLE,
                IconSourse.BACK + "", View.VISIBLE));
        headsecond_layout.setClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!MyApp.ReadOnly) {
                    isRefesh = true;
                    switch (type) {
                        case Constant.EdMeterial://典设添加模块、材料
                            Map<String, Object> map = new HashMap<>();
                            map.put("cid", codeset_id);
                            map.put("type", "典设");
                            PopwindowUtil.openPop((TextView) view, mActivity, DataUtil.getMaterialItem(map));
                            break;
                        case Constant.EdModel://模块添加材料
                            IntentToNext(MString.Modular_Pro);
                            break;
                        default:
                            IntentToNext(MString.MaterialScience);
                            break;
                    }
                }
            }
        });
        if (MyApp.ReadOnly) {
            headsecond_layout.mRightTitle.setVisibility(View.INVISIBLE);
        }
    }

    private void IntentToNext(String type) {

        Bundle bundle = new Bundle();
        bundle.putString(MString.TYPE, type);
        bundle.putString(MString.ERROR, codeset_id);
        IntentToActivity.intent(MyApp.activity, MultiselectActivity.class, bundle);
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onResume() {
        mActivity = this;
        MyApp.activity = this;
        if (type == Constant.EDIT) {
            UpdateOrAdd();
        }
        if (isRefesh) initialization();
        super.onResume();
    }

    @Override
    protected void findView() {
        //new
        layoutDel = (LinearLayout) findViewById(R.id.design_view2);
        checkBox = (CheckBox) findViewById(R.id.dd_cbox);
        checkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String small = "0";
                        if (checkBox.isChecked()) {
                            small = "1";
                        }
                        for (MaterialBean bean : data) {
                            bean.setBig_category("1");
                            bean.setMiddle_category(small);
                        }
                        handler.sendEmptyMessage(8);
                    }
                }).start();
            }
        });
        TextView tvDel = (TextView) findViewById(R.id.dd_tv_del);
        SetTypeface.set(tvDel, IconSourse.DELECT);
        tvDel.append(" 删除");
        delList = new ArrayList<>();
        tvDel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showWaitDialog(-1, "处理...");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        delList.clear();
                        for (MaterialBean bean : data) {
                            if (bean.getMiddle_category() != null && bean.getMiddle_category().equals("1")) {
                                delList.add(bean);
                            }
                        }
                        count = -1;
                        handler.sendEmptyMessage(7);
                    }
                }).start();
            }
        });
        //取消
        findViewById(R.id.dd_tv_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (layoutDel.getVisibility() == View.VISIBLE) {
                    layoutDel.setVisibility(View.GONE);
                }
                for (MaterialBean bean : data) {
                    bean.setBig_category("0");
                    bean.setMiddle_category("0");
                }
                isLong = false;
                codeset_list.update();
            }
        });
        //old
        codeset_list = (SwipeRefreshListView) findViewById(R.id.design_list);
        codeset_list.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (layoutDel.getVisibility() == View.VISIBLE) {
                    layoutDel.setVisibility(View.GONE);
                    isLong = false;
                }
                if (type == Constant.EDIT) {
                    UpdateOrAdd();
                } else if (type == Constant.EdModel) {
                    MyApp.HTTP.getModelMaterialList1(handler, HttpStringUtil.SUCCESSED, codeset_id);
                } else {
                    MyApp.HTTP.getCodeSetMaterialList(handler, HttpStringUtil.SUCCESSED, codeset_id);
                }
            }
        });
        setDelectStyle();
        super.findView();
        initialization();
    }

    private int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                getResources().getDisplayMetrics());
    }

    @Override
    protected void initialization() {
        super.initialization();
        if (layoutDel.getVisibility() == View.VISIBLE) {
            layoutDel.setVisibility(View.GONE);
        }
        if (type == Constant.EDIT) {
            AddNowHandler();
            UpdateOrAdd();
        } else if (type == Constant.EdModel) {
            AddHandler();
            MyApp.HTTP.getModelMaterialList1(handler, HttpStringUtil.SUCCESSED, codeset_id);//加载全部
        } else {
            AddHandler();
            MyApp.HTTP.getCodeSetMaterialList(handler, HttpStringUtil.SUCCESSED, codeset_id);//加载全部
        }


    }

    private void UpdateOrAdd() {
        MyApp.HTTP.getQueryExpCodeset(NowHandler, HttpStringUtil.SUCCESSED, MyApp.currExploration.getExploration_id());
    }

    /**
     * 加载侧滑删除样式*
     */
    private void setDelectStyle() {
        if (!MyApp.ReadOnly) {
            upExpMaterialHandler();
            SwipeMenuCreator creator = new SwipeMenuCreator() {
                @Override
                public void create(SwipeMenu menu) {
                    SwipeMenuItem deleteItem = new SwipeMenuItem(getApplicationContext());
                    deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9,
                            0x3F, 0x25)));
                    deleteItem.setWidth(dp2px(90));
                    deleteItem.setIcon(R.mipmap.ic_delete);
                    menu.addMenuItem(deleteItem);
                }
            };
            codeset_list.setMenuCreator(creator, new SwipeMenuListView.OnMenuItemClickListener() {
                @Override
                public void onMenuItemClick(int position, SwipeMenu menu, int index) {
                    mposition = position;
                    delItemData(data.get(position), 10);
                }
            });
            codeset_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    if (isLong) {
                        final MaterialBean bean1 = data.get(i);
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                for (MaterialBean bean : data) {
                                    bean.setBig_category("1");
                                    if (bean.getSpec().equals(bean1.getSpec())) {
                                        if (bean1.getMiddle_category() != null && bean1.getMiddle_category().equals("1")) {
                                            bean.setMiddle_category("0");
                                        } else {
                                            bean.setMiddle_category("1");
                                        }
                                    }
                                }
                                boolean isAll = true;
                                for (MaterialBean bean : data) {
                                    if (bean.getMiddle_category() != null && bean.getMiddle_category().equals("0")) {
                                        isAll = false;
                                    }
                                }
                                Message message = handler.obtainMessage();
                                message.obj = isAll;
                                message.what = 9;
                                handler.sendMessage(message);
                            }
                        }).start();
                    } else {
                        cposition = i;
                        MyDialog.dialogForUpExpMaterial(type, mActivity, data.get(i), upExpMaterialHandler);
                    }
                }
            });
            //长按批量删除
            codeset_list.setOnItemLongClicklistener(new AdapterView.OnItemLongClickListener() {
                @Override
                public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                    if (isLong) return false;
                    if (layoutDel.getVisibility() == View.GONE) {
                        layoutDel.setVisibility(View.VISIBLE);
                    }
                    MaterialBean bean1 = data.get(position);
                    for (MaterialBean bean : data) {
                        bean.setBig_category("1");
                        if (bean.getSpec().equals(bean1.getSpec())) {
                            bean.setMiddle_category("1");
                        } else {
                            bean.setMiddle_category("0");
                        }
                    }
                    isLong = true;
                    codeset_list.update();
                    return true;
                }
            });

        }
    }

    private void delItemData(MaterialBean bean, int index) {
        String id = bean.getCodeset_material_id();
        if (type == Constant.EdModel) {
            MyApp.HTTP.DelProModelMaterial(handler, index, id);
        } else {
            MyApp.HTTP.DelProDetailMaterial(handler, index, id);
        }
    }


    /**
     * 获取典设明细材料handler*
     */
    private void AddHandler() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            if (data == null) {
                                data = FastJsonUtil.JsonToData_CodeSetMaterialList((String) msg.obj);
                            } else {
                                data.clear();
                                data.addAll(FastJsonUtil.JsonToData_CodeSetMaterialList((String) msg.obj));
                            }
                            handler.sendEmptyMessage(ADDADAPTER);
                            //nx缓存点设材料到本地
                            if (type == Constant.EdMeterial) {
                                String key = MString.nxDsMaterial + codeset_id;
                                ShardPreferencesTool.save(getApplicationContext(), key, FastJsonUtil.beanToJson(data), 3);
                            }
                        }
                        break;
                    case ADDADAPTER:
                        codeset_list.setRefreshing(false);
                        if (adapter == null) {
                            adapter = new MaterialDetailAdapter(data, mActivity, type);
                            codeset_list.setAdapter(adapter);
                        } else {
                            codeset_list.update();
                        }
                        break;
                    case HttpStringUtil.ERROR:
                        break;
                    case 7://for循环删除材料
                        if (delList.isEmpty()) {
                            ToastShow.showShort(mActivity, "未选中任何材料");
                            hideWaitIngDialog();
                            return;
                        }
                        count++;
                        if (count < delList.size()) {
                            delItemData(delList.get(count), 7);
                        } else {
                            count = -1;
                            isLong = false;
                            delList.clear();
                            hideWaitIngDialog();
                            initialization();
                            if (layoutDel.getVisibility() == View.VISIBLE) {
                                layoutDel.setVisibility(View.GONE);
                            }
                        }
                        break;
                    case 8:
                        codeset_list.update();
                        break;
                    case 9:
                        checkBox.setChecked((Boolean) msg.obj);
                        codeset_list.update();
                        break;
                    case 10://单个删除材料
                        String s = FastJsonUtil.JsonToCheck_String((String) msg.obj);
                        if (s.equals(MString.TRUE)) {
                            ToastShow.showShort(mActivity, MString.SUCCESSED_HTTP);
                        } else {
                            ToastShow.showShort(mActivity, "删除失败");
                        }
                        codeset_list.setRefreshing(true);
                        initialization();
                        break;
                }
            }
        };
    }

    /**
     * 获取典设材料handler*
     */
    private void AddNowHandler() {
        NowHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            if (data != null) {
                                data.clear();
                                data.addAll(FastJsonUtil.JsonToData_CodeSetMaterial_List((String) msg.obj));
                            } else {
                                data = FastJsonUtil.JsonToData_CodeSetMaterial_List((String) msg.obj);
                            }
                            NowHandler.sendEmptyMessage(ADDADAPTER);
                        }
                        break;
                    case ADDADAPTER:
                        if (adapter == null) {
                            adapter = new MaterialDetailAdapter(data, mActivity, type);
                            codeset_list.setAdapter(adapter);
                        } else {
                            codeset_list.update();
                            codeset_list.setRefreshing(false);
                        }
                        break;
                    case HttpStringUtil.ERROR:
                        break;

                }
            }
        };
    }

    /**
     * 修改踏勘典设材料数量handler*
     */
    private void upExpMaterialHandler() {
        upExpMaterialHandler = new Handler() {
            double num = -1;
            String type;

            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            upExpMaterialHandler.sendEmptyMessage(2);
                        }
                        break;
                    case 1://设置修改后结果
                        num = Double.valueOf(String.valueOf(msg.obj));
                        type = MString.NEW;
                        data.get(cposition).setNum(num + "");
                        data.get(cposition).setUse_type(type);
                        codeset_list.update();
                        break;
                    case 2:
                        if (num == -1) return;
                        data.get(cposition).setNum(num + "");
                        data.get(cposition).setUse_type(type);
                        codeset_list.update();
//                        UpdateOrAdd();
                        initialization();
                        break;
                    case HttpStringUtil.ERROR:
                        ToastShow.showShort(mActivity, "修改失败！");
                        break;

                }
            }
        };
    }

}
